<template>
    <view class="login-container">
        <image src="../../static/loginBg.png" class="background-img"></image>
        <view class="absolve-wrapper">
            <view class="logo">
                <image src="../../static/logo.png" class="logo-img"></image>
            </view>
            <view class="text-title">群晖音乐随心听</view>
            <view class="login-main">
                <view class="input-wrapper">
                    <i class="iconfont icon-liebiao icon"></i>
                    <input placeholder="http://www.xxx.xxx:5000" v-model="rootUrl" maxlength="-1"
                        style="width: 100%;" />
                </view>
                <view class="input-wrapper">
                    <i class="iconfont icon-phone icon"></i>
                    <input placeholder="请输群晖账号" v-model="userId" maxlength="11" />
                </view>
                <view class="input-wrapper">
                    <i class="iconfont icon-password icon"></i>
                    <input v-if="isText" type="text" placeholder="请输入密码" v-model="password" />
                    <input v-else type="password" placeholder="请输入密码" v-model="password" />
                    <i class="iconfont eye" :class="isText ? 'icon-openEye' : 'icon-closeEye'"
                        @click="isText = !isText"></i>
                </view>
                <button class="cu-btn round login-button lg cu-load" :class="{ loading: loading }"
                    @click="qunhuiLoginV7()">登录</button>
            </view>
            <view class="other-login">
                <view class="other-text">第三方登录</view>
                <view class="login-list">
                    <i class="iconfont icon-weixin other-item" @click="handleTest"></i>
                    <i class="iconfont icon-qq other-item" @click="handleTest"></i>
                    <i class="iconfont icon-weibo other-item" @click="handleTest"></i>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                loading: false,
                isText: false,
                //群晖地址
                rootUrl: null,
                //登录参数
                userId: '',
                password: '',
                //群晖加密参数
                Encryption: {}
            };
        },
        methods: {
            getUserInfo() {
                this.loading = true;
                let that = this;
                //测试账号，可以改成你自己的
                const userInfo = this.userInfo;
                that.loading = true;
                uni.setStorageSync('ROOT_URL', this.rootUrl)
                uni.setStorageSync('LOGIN_USER_INFO', this.userInfo)
                this.qunhuiLoginV7()
            },
            handleTest() {
                uni.showToast({
                    title: '功能开发中哦...',
                    icon: 'none',
                    duration: 2000
                });
            },
            /**
             * 登录前获取群晖的加密参数
             */
            getEncryption() {
                //audio station 登录前调用的
                this.$post('/webapi/encryption.cgi/SYNO.API.Encryption', {
                    api: 'SYNO.API.Encryption',
                    method: 'getinfo',
                    version: 1,
                    format: 'module'
                }, ).then(data => {
                    // console.log('[信息]群晖的加密参数', data)
                    this.Encryption = data
                })
            },
            /**
             * 群晖登录
             */
            qunhuiLoginV7() {
                let that = this;
                uni.setStorageSync('ROOT_URL', this.rootUrl)
                this.$config.host = this.rootUrl
                uni.setStorageSync('LOGIN_USER_INFO', {
                    userId: this.userId,
                    password: this.password
                })
                let params = {
                    api: 'SYNO.API.Auth',
                    account: this.userId,
                    passwd: this.password,
                    version: 7,
                    method: 'login',
                    session: 'webui',
                    enable_syno_token: 'yes',
                    client: 'uniapp',
                    enable_device_token: 'yes',
                    is_portal_port: 'yes',
                    rememberme: 1,
                    timezone: this.stdTimezone(),
                    //随机数
                    tabid: Math.random() * (99999 - 10000).toFixed(0) + 10000,
                }
                let url = this.$config.host + '/webapi/entry.cgi?api=SYNO.API.Auth'
                console.log('[信息]登录参数', params)
                uni.request({
                    url: url,
                    data: params,
                    header: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'X-SYNO-HASH': 'uniapp',
                    },
                    method: "POST",
                    success: (response) => {
                        if (response.statusCode === 200) {
                            if (response.cookies && response.cookies.length > 0) {
                                console.log('[信息]请求cookies', response.cookies)
                                let cookies = ''
                                response.cookies.map(cookie => {
                                    cookies += cookie + ';'
                                })
                                this.$config.cookie = cookies
                                uni.setStorageSync('COOKIES', this.$config.cookie)
                                console.log('[信息]cookies', cookies)
                            }
                            that.loading = false;
                            const data = response.data;
                            console.log('[信息]群晖登录返回参数', data)
                            if (data.success) {
                                that.$clearCache()
                                that.$config.sid = data.data.sid
                                that.validateToken(data.data.synotoken)
                                uni.setStorageSync('LOGIN_RESULT', data.data)
                            } else {
                                uni.showToast({
                                    title: '登录失败',
                                    icon: 'none'
                                });
                            }
                        } else {
                            uni.showToast({
                                title: '登录失败:' + response.statusCode,
                                icon: 'none'
                            });
                        }
                    },
                    fail: (error) => {
                        uni.showToast({
                            title: '登录失败:' + error,
                            icon: 'none'
                        });
                    },
                });

            },
            /**
             * 返回时间戳
             */
            stdTimezone: function() {
                var e = (new Date).getFullYear(),
                    t = new Date(e, 0, 1).getTimezoneOffset(),
                    i = new Date(e, 6, 1).getTimezoneOffset(),
                    s = t >= i ? t : i;
                return (s > 0 ? "-" : "+") + ("" + Math.abs(s / 60)).padStart(2, "0") + ":" + ("" + Math.abs(s %
                    60)).padStart(2, "0")
            },
            /**
             * 验证synotoken
             * @param {Object} synotoken
             */
            validateToken(synotoken) {
                this.$config.synotoken = synotoken
                uni.navigateTo({
                    url: '/pages/index/index'
                });
            }
        },
        /**
         * 初始化挂载时
         */
        mounted() {

        },
        onLoad(e) {
            //自动登录
            if (uni.getStorageSync("LOGIN_RESULT") && uni.getStorageSync('COOKIE') && e.statusCode != 401) {
                this.reloadLoginInfo()
                uni.reLaunch({
                    url: '/pages/index/index'
                })
                return
            }
            this.rootUrl = uni.getStorageSync('ROOT_URL');
            let userInfo = uni.getStorageSync('LOGIN_USER_INFO')
            console.log('初始化挂载时', userInfo)
            if (userInfo) {
                this.userId = userInfo.userId;
                this.password = userInfo.password;
            }
            this.getEncryption()
        }
    };
</script>

<style lang="scss" scoped>
    .login-container {
        width: 100%;
        height: 100vh;
        position: relative;
        overflow: hidden;

        // background: url(../../static/loginBg.png) no-repeat;
        // background-size: contain;
        .absolve-wrapper {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        .background-img {
            width: 100%;
            height: 100%;
        }

        .logo {
            text-align: center;
            margin-top: 12%;

            .logo-img {
                width: 100px;
                height: 100px;
            }
        }

        .text-title {
            font-size: 48rpx;
            margin-top: 5%;
            text-align: center;
            color: #fffefe;
        }

        .login-main {
            box-sizing: border-box;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            left: 10%;
            right: 10%;

            .input-wrapper {
                display: flex;
                align-items: center;
                margin-bottom: 30rpx;
                padding-bottom: 30rpx;
                border-bottom: 1px solid rgb(242, 242, 242);
                position: relative;

                .icon {
                    margin-right: 10px;
                    font-size: 16px;
                }

                .eye {
                    float: right;
                    position: absolute;
                    right: 5px;
                    font-size: 16px;
                }
            }

            .login-button {
                width: 100%;
                color: #fff;
                background-image: linear-gradient(to right, #ffa6b6, #ff7c93);
                letter-spacing: 2px;
                height: 45px;
                margin-top: 75rpx !important;
            }
        }

        .other-login {
            position: absolute;
            bottom: 5%;
            left: 10%;
            right: 10%;

            .other-text {
                text-align: center;
                color: rgba(0, 0, 0, 0.4);
                font-size: 28rpx;
                position: relative;

                &::before,
                &::after {
                    position: absolute;
                    background: rgba(0, 0, 0, 0.15);
                    content: '';
                    height: 1px;
                    top: 50%;
                    width: 100px;
                }

                &::before {
                    left: 5px;
                }

                &::after {
                    right: 5px;
                }
            }

            .login-list {
                margin-top: 15px;
                display: flex;
                justify-content: center;
                align-items: center;

                .other-item {
                    flex: 1;
                    font-size: 40px;
                    text-align: center;

                    &.icon-weixin {
                        color: #17d874;
                    }

                    &.icon-qq {
                        color: #32d6f5;
                    }

                    &.icon-weibo {
                        color: rgb(234, 93, 92);
                    }

                }
            }
        }

        /deep/ {
            .input-placeholder {
                color: rgb(194, 194, 194);
                font-size: 30rpx;
            }
        }
    }
</style>
